package com.huiben.app.cartoonbooks.service;

import android.app.Service;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.huiben.app.cartoonbooks.app.DownloadAsyncTask;
import com.huiben.app.cartoonbooks.app.FrameBean;
import com.huiben.app.cartoonbooks.listener.onPlayListener;
import com.huiben.app.cartoonbooks.utils.SystemUtil;
import com.kymjs.rxvolley.BuildConfig;
import com.kymjs.rxvolley.toolbox.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.Timer;
import java.util.TimerTask;

public class PlayerService extends Service {

    private static final String TAG = PlayerService .class.getSimpleName();
    private MediaPlayer mMediaPlayer;
    private boolean isDownload;//是否下载完成了
    private long mTotalSize; // 下载文件大小
    private long totalKbRead; // 已读取的最终文件KB大小
    private long oldTotalKbRead = 0; // 旧的缓存大小,一开始为0

    private onPlayListener mPlayListener;
    private int palyPosition;
    private boolean isWait = false;
    private DownloadAsyncTask mDownloadAsyncTask;
    private Timer mTimer;
    private long mDuration = 0;
    private boolean isPause = false;
    private boolean isStop = false;
    TimerTask mTimerTask = null;

//    private Broadcast.DataEntity mDataEntity;
//
//    public Broadcast.DataEntity getDataEntity() {
//        return mDataEntity;
//    }

    private Handler handleProgress = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (mMediaPlayer != null && mMediaPlayer.isPlaying() && mPlayListener != null) {
                mPlayListener.onPlay(mMediaPlayer.getCurrentPosition());
            }
        }
    };

    public void stopTimer() {
        if (mTimer != null) {
            mTimer.cancel();
        }
        if (mTimerTask != null) {
            mTimerTask.cancel();
        }
        if (BuildConfig.DEBUG)
            Log.d("PlayerService", "stopTimer");
        mTimer = null;
        mTimerTask = null;
    }

    public void startTimer() {
        if (mTimer != null || mTimerTask != null) {
            stopTimer();
        }
        if (BuildConfig.DEBUG)
            Log.e("PlayerService", "startTimer");
        mTimer = new Timer();
        mTimerTask = new TimerTask() {
            @Override
            public void run() {
                if (mMediaPlayer != null && mMediaPlayer.isPlaying() && mPlayListener != null) {
                    handleProgress.sendEmptyMessage(0);
                }
            }
        };
        mTimer.schedule(mTimerTask, 0, 1000);
    }

    public PlayerService() {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mMediaPlayer.setOnCompletionListener(new MyCompletionListener());
        mMediaPlayer.setLooping(false);
    }

    @Override
    public void onCreate() {
        super.onCreate();
    }

    public void pause() {
        if (mMediaPlayer.isPlaying()) {
            mMediaPlayer.pause();
            isPause = true;
        } else if (!mMediaPlayer.isPlaying() && isWait) {
            isPause = true;
        }
        if (mPlayListener != null) {
            mPlayListener.onPause();
        }
    }

    public void continuePlay() {
        if (isPause) {
            if (isDownload) {
                mMediaPlayer.start();
            }
        }
        isPause = false;
        if (mPlayListener != null) {
            mPlayListener.onContinuePlay();
        }
    }

    private void initVariable() {
        isPause = false;
        palyPosition = 0;
        totalKbRead = 0;
        mTotalSize = 0;
        oldTotalKbRead = 0;
        isDownload = false;
        isWait = false;
        mDuration = 0;
    }

    public void stop() {
        if (isPlaying()) {
            isStop = true;
            stopTimer();
            if (isDownload) {
                mMediaPlayer.stop();
            } else {
                if (mMediaPlayer.isPlaying() || isPause) {
                    // 停止下载，停止播放
                    mMediaPlayer.stop();
                    mMediaPlayer.reset();
                    //mMediaPlayer.release();

                    if (mDownloadAsyncTask != null) {
                        if (!mDownloadAsyncTask.isCancelled()) {
                            mDownloadAsyncTask.setDwon(false);
                            mDownloadAsyncTask.cancel(true);
                        }
                        mDownloadAsyncTask = null;
                    }
                } else if (isWait) {

                    if (mDownloadAsyncTask != null) {
                        if (!mDownloadAsyncTask.isCancelled()) {
                            mDownloadAsyncTask.setDwon(false);
                            mDownloadAsyncTask.cancel(true);
                        }
                        mDownloadAsyncTask = null;
                    }
                }
            }
            initVariable();
            if (mPlayListener != null) {
                mPlayListener.onStop();
            }
        }
    }

    public float getCacheProgress() {
        if (isDownload) {
            return 1;
        } else {
            return (float) (((double) totalKbRead) / ((double) mTotalSize));
        }
    }

    public long getProgress() {
        if (mMediaPlayer.isPlaying() || isPause) {
            return mMediaPlayer.getCurrentPosition();
        } else if (!mMediaPlayer.isPlaying() && isWait) {
            return palyPosition;
        }
        return 0;
    }

    public boolean isPause() {

        return isPlaying() && isPause;
    }

    public boolean isPlaying() {
        if (mMediaPlayer.isPlaying() || isPause) {
            return true;
        } else if (!mMediaPlayer.isPlaying() && isWait) {
            return true;
        }
        return false;
    }

    public void setPlayListener(onPlayListener playListener) {
        mPlayListener = playListener;
    }

    public void playInInternet( String url) {
        Log.e(TAG, "playInInternet: " );
        if (isPause) {
            continuePlay();
            return;
        }
        if (!mMediaPlayer.isPlaying()) {
                //单个音频
//             String url = dataEntity.getAudiopath()+dataEntity.getAudioname().get(0);
//            mDataEntity = dataEntity;
            isStop = false;
            String fileName = SystemUtil.textToMD5L32(url);
            final File file = new File(FileUtils.getSaveFolder("MyFM"), fileName);

            Log.e(TAG, "playInInternet:fileName "+ fileName +":: file path"+file.getAbsolutePath());
            if (file.exists()) {
                // 已经存在缓存，判断是否完整的
                File file1 = new File(file.getParent(), file.getName() + ".ok");
                if (file1.exists()) {
                    // 直接播放缓存

                        Log.e("PlayerService", "直接播放缓存");
                    oldTotalKbRead = 1;
                    totalKbRead = 1;
                    isDownload = true;
                    if (mPlayListener != null) {
                        mPlayListener.onCache(1);

                            Log.e("PlayerService", "onCache");
                    }
                    playNet(file, 0);
                } else {

                        Log.e("PlayerService", "删掉文件，重新缓存");
                    file.delete();
                    cachePlay(url, file);
                }
            } else {
                // 不存在缓存，去进行网络边缓存边播放
                cachePlay(url, file);
            }
        }
    }

    public void seekTo(int position) {
        if (mMediaPlayer != null) {

                Log.e("PlayerService", "mDuration:" + mDuration);

                Log.e("PlayerService", "position:" + position);


                Log.e("PlayerService", "mTotalSize:" + mTotalSize);
            oldTotalKbRead = (long) (((double) position) / ((double) mDuration) * ((double) mTotalSize));
            Log.d("PlayerService", "oldTotalKbRead:" + oldTotalKbRead);
            if (!mMediaPlayer.isPlaying() && isWait) {
                palyPosition = position;
            } else if (mMediaPlayer.isPlaying() && isDownload) {
                mMediaPlayer.seekTo(position);
            } else if (mMediaPlayer.isPlaying() && !isDownload) {
                if (((double) position) / ((double) mDuration) > ((double) totalKbRead) / ((double) mTotalSize)) {
                    palyPosition = position;
                    isWait = true;
                    mMediaPlayer.stop();
                    mMediaPlayer.reset();
                    // mMediaPlayer.release();
                    mTimer.cancel();
                    // oldTotalKbRead = position / getDuration() * mTotalSize;
                } else {
                    mMediaPlayer.seekTo(position);
                }
            }
        }
    }

    private void cachePlay(String url, final File file) {
        if (mDownloadAsyncTask != null) {
            if (!mDownloadAsyncTask.isCancelled()) {
                mDownloadAsyncTask.setDwon(false);
                mDownloadAsyncTask.cancel(true);
            }
            mDownloadAsyncTask = null;
        }
        mDownloadAsyncTask = new DownloadAsyncTask(new DownloadAsyncTask.onDownloadListener() {
            @Override
            public void onProgress(long transferredBytes, long totalSize) {

                if (mTotalSize == 0)
                    mTotalSize = totalSize / 1024;
                //回调缓存的百分比
                if (mPlayListener != null) {
                    mPlayListener.onCache(((float) transferredBytes) / ((float) totalSize));
                }
                totalKbRead = transferredBytes / 1024;
                if (oldTotalKbRead < 1 && totalKbRead - oldTotalKbRead > 200 && !isStop) {
                    oldTotalKbRead = totalKbRead;
                    // 第一次开始播放了

                        Log.e("PlayerService", "第一次开始播放了");
                    PlayerService.this.playNet(file, 0);
                } else if (isWait && !isDownload && totalKbRead - oldTotalKbRead > 200) {
                    // 再次进行播放

                        Log.e("PlayerService", "再次进行播放");
                    isWait = false;
                    oldTotalKbRead = totalKbRead;
                    PlayerService.this.playNet(file, palyPosition);
                }
            }
            //下载成功了

            @Override
            public void onSuccess() {
                isDownload = true;
                if (isWait) {
                    isWait = false;

                }
                PlayerService.this.playNet(file, palyPosition);
//                if (mPlayListener != null) {
//                    mPlayListener.onSuccess();
//                }
            }

            @Override
            public void onFailure() {
                if (mPlayListener != null) {
                    mPlayListener.onFailure();
                }
            }
        });
        mDownloadAsyncTask.execute(file.getAbsolutePath(), url);
    }

    private void playNet(File file, int palyPosition) {
        try {
            mMediaPlayer.reset();

                Log.e("PlayerService", file.getAbsolutePath());
            mMediaPlayer.setDataSource(file.getAbsolutePath());
            mMediaPlayer.setOnPreparedListener(new MyPreparedListener(palyPosition));
            mMediaPlayer.prepareAsync();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public long getDuration() {
        return mMediaPlayer.getDuration();
    }

    private class MyCompletionListener implements MediaPlayer.OnCompletionListener {

        @Override
        public void onCompletion(MediaPlayer mp) {
            mMediaPlayer.reset();
            // mMediaPlayer.release();
            stopTimer();
            // 判断是否已经缓存完成

                Log.e("MyCompletionListener", "判断是否已经缓存完成");
            if (!isDownload) {

                    Log.e("MyCompletionListener", "palyPosition:" + palyPosition);

                palyPosition = (int) (((double) oldTotalKbRead) / ((double) totalKbRead) * ((double) getDuration()));
                isWait = true;
            } else {
                Log.e(TAG, "onCompletion:下载完成" );
                if (mPlayListener != null) {
                    mPlayListener.onSuccess();
                }
            }
        }
    }

    private class MyPreparedListener implements MediaPlayer.OnPreparedListener {

        private int playPosition;

        public MyPreparedListener(int playPosition) {
            this.playPosition = playPosition;
        }

        @Override
        public void onPrepared(MediaPlayer mp) {
            if (mPlayListener != null) {
                mDuration = mMediaPlayer.getDuration();
                mPlayListener.onStart(mDuration);
            }
            startTimer();
            mMediaPlayer.start();
            if (playPosition > 0) {
                mMediaPlayer.seekTo(playPosition);
            }
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }

   public class MyBinder extends Binder {
        public PlayerService getService() {
            return new PlayerService();
        }
    }

    @Override
    public void onDestroy() {
        stopTimer();
        if (mDownloadAsyncTask != null) {
            if (!mDownloadAsyncTask.isCancelled()) {
                mDownloadAsyncTask.setDwon(false);
                mDownloadAsyncTask.cancel(true);
            }
            mDownloadAsyncTask = null;
        }
        if (mMediaPlayer != null && mMediaPlayer.isPlaying()) {
            mMediaPlayer.stop();
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
        super.onDestroy();
    }
}
